package com.wh.message.utils;

import com.wh.common.util.Result;
import com.wh.msg.ResultCode;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 参数校验类
 * @author 谢泽鹏
 * @version V1.0
 * @Package com.wh.message.voice.service
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
public class ValidatorFactoryUtil {

    private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    /**
     * 参数效验
     * @param t    验证模型
     * @param <T>  返回模型
     * @return
     */
    public static <T> Result validate(T t) {
        Result result = new Result();
        result.setResCode(ResultCode.RES_OK);
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
        for (ConstraintViolation<T> constraintViolation : constraintViolations) {
            result.setResCode(ResultCode.RES_2000);
            result.setResMsg(constraintViolation.getMessage());
            return result;
        }
        return result;
    }
}
